//
//  RotationTabViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 6/9/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "RotationTabViewController.h"

#import "UIManager.h"

#import <QuartzCore/QuartzCore.h>

#import <FacebookSDK/FacebookSDK.h>

#import "RotationTabTableViewCell.h"

#import "AppDelegate.h"

#import "IIViewDeckController.h"

@interface RotationTabViewController (){

    int x;
    int c;
    int z;
    NSString *hideValue;
    NSArray *arrayTabs;
}

@end

@implementation RotationTabViewController



// Implement the check for displaying the back link
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (delegate.refererAppLink) {
        self.backLinkInfo = delegate.refererAppLink;
        [self _showBackLink];
    }
    delegate.refererAppLink = nil;
    
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.tableView setBackgroundColor:[UIColor colorWithRed:35.0/255.0 green:35.0/255.0 blue:35.0/255.0 alpha:1.0]];
    
    
    arrayTabs = [[NSArray alloc] initWithObjects:@"HOME", @"NEWSFEED", @"ARTIST", @"TOP DOWNLOADS", @"PLAYLIST", @"EVENTS", @"FAVORITES", nil];

}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    return 7;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    static NSString *cellIdentifier = @"Cell";
    
    RotationTabTableViewCell *cell = (RotationTabTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"RotationTabTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    cell.captionChooserLbl.text = [arrayTabs objectAtIndex:indexPath.row];
    
    
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];
    
    
    if ([cell.captionChooserLbl.text isEqualToString:@"HOME"]) {
        cell.imgLogo.image = [UIImage imageNamed:@"homeLogo.png"];
    }else if ([cell.captionChooserLbl.text isEqualToString:@"NEWSFEED"]){
        cell.imgLogo.image = [UIImage imageNamed:@"newsLogo.png"];
    }else if ([cell.captionChooserLbl.text isEqualToString:@"ARTIST"]){
        cell.imgLogo.image = [UIImage imageNamed:@"artistLogo.png"];
    }else if ([cell.captionChooserLbl.text isEqualToString:@"TOP DOWNLOADS"]){
        cell.imgLogo.image = [UIImage imageNamed:@"topLogo.png"];
    }else if ([cell.captionChooserLbl.text isEqualToString:@"PLAYLIST"]){
        cell.imgLogo.image = [UIImage imageNamed:@"playlistLogo.png"];
    }else if ([cell.captionChooserLbl.text isEqualToString:@"EVENTS"]){
        cell.imgLogo.image = [UIImage imageNamed:@"eventsLogo.png"];
    }else if ([cell.captionChooserLbl.text isEqualToString:@"FAVORITES"]){
        cell.imgLogo.image = [UIImage imageNamed:@"favLogo.png"];
    }
    
    
    return cell;
}


#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSLog(@"TAB CHOOSE = %@", [arrayTabs objectAtIndex:indexPath.row]);
    
    
    
    
    switch (indexPath.row) {
            
        case 0:
            
            self.viewDeckController.centerController = [[UIManager sharedItems] homePageViewController];
            [self.viewDeckController closeLeftViewAnimated:YES];
            
            break;
            
        case 1:
            
            self.viewDeckController.centerController = [[UIManager sharedItems] newsFeedViewController];
            [self.viewDeckController closeLeftViewAnimated:YES];
            
            break;
            
        case 2:
            
            self.viewDeckController.centerController = [[UIManager sharedItems] artistViewController];
            [self.viewDeckController closeLeftViewAnimated:YES];
            
            break;
            
        case 3:
            
            self.viewDeckController.centerController = [[UIManager sharedItems] topDownloadedViewController];
            [self.viewDeckController closeLeftViewAnimated:YES];
            
            break;
            
        case 4:
            
            self.viewDeckController.centerController = [[UIManager sharedItems] playListViewController];
            [self.viewDeckController closeLeftViewAnimated:YES];
            
            break;
            
        case 5:
            
            self.viewDeckController.centerController = [[UIManager sharedItems] eventsViewController];
            [self.viewDeckController closeLeftViewAnimated:YES];
            
            break;
            
        case 6:
            
            self.viewDeckController.centerController = [[UIManager sharedItems] favoritesViewController];
            [self.viewDeckController closeLeftViewAnimated:YES];
            
            
            break;
            
            
        default:
            break;
    }
    
    
}



////////////

- (IBAction)nextAction:(id)sender {
    
    NSLog(@"Next");
    
    [UIView animateWithDuration:0.5 animations:^{
        
        float degrees = -51.43; //the value in degrees
        self.dialImg.transform = CGAffineTransformRotate(self.dialImg.transform, degrees * M_PI/180);
        
        NSLog(@"center of dial img x = %f and y = %f", self.dialImg.frame.origin.x ,self.dialImg.frame.origin.y);
        
    }completion:^(BOOL finished){
       
        
        if(x == ([self.viewControllers count] - 1)){ /// kapag siya na ung pinaka last na slider mo
            x = 0;
            NSLog(@"slider value last = %@", [self.viewControllers objectAtIndex:x]);
            
            
//            [[[UIManager sharedItems] favoritesViewController].view removeFromSuperview];
            [self.view insertSubview:[[UIManager sharedItems] homePageViewController].view belowSubview:self.sliderContainerView];

           // self.scrollViews.contentOffset = CGPointMake(0,0);
            //[self.view insertSubview:self.scrollHomeView belowSubview:self.sliderContainerView];
            
        }else{
            x = x + 1; /// Declare mo ung next slider
            
            NSString *view = [self.viewControllers objectAtIndex:x];
            
            if ([view isEqualToString:@"NewsFeedView"]) {
                
                NSLog(@"slider value next = %@",view);

//                    self.scrollViews.contentOffset = CGPointMake(320,0);
                
               
                
                
                [[[UIManager sharedItems] homePageViewController].view removeFromSuperview];
//
                [self.view insertSubview:[[UIManager sharedItems] newsFeedViewController].view belowSubview:self.sliderContainerView];
//                [self.view insertSubview:self.scrollNewsFeedView belowSubview:self.sliderContainerView];
                
                
            } else if([view isEqualToString:@"ArtistView"]) {
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] newsFeedViewController].view removeFromSuperview];
//
//                [self.view insertSubview:self.scrollArtistView belowSubview:self.sliderContainerView];
                
                [self.view insertSubview:[[UIManager sharedItems] artistViewController].view belowSubview:self.sliderContainerView];
                //self.scrollViews.contentOffset = CGPointMake(640,0);
                

            }else if ([view isEqualToString:@"TopDownloadedView"]){
                
                NSLog(@"slider value next = %@",view);

            //    self.scrollViews.contentOffset = CGPointMake(960,0);
                
                [[[UIManager sharedItems] artistViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] topDownloadedViewController].view belowSubview:self.sliderContainerView];
                
               // [self.view insertSubview:self.scrollArtistView belowSubview:self.sliderContainerView];
            
            }else if ([view isEqualToString:@"PlayListView"]){
            
                NSLog(@"slider value next = %@",view);
                
             //   self.scrollViews.contentOffset = CGPointMake(1280,0);
                
                [[[UIManager sharedItems] topDownloadedViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] playListViewController].view belowSubview:self.sliderContainerView];
            
            }else if ([view isEqualToString:@"EventsView"]){
            
                NSLog(@"slider value next = %@",view);
                
            //    self.scrollViews.contentOffset = CGPointMake(1600,0);
                
                [[[UIManager sharedItems] playListViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] eventsViewController].view belowSubview:self.sliderContainerView];
            
            }else if ([view isEqualToString:@"FavoritesView"]){
            
                NSLog(@"slider value next = %@",view);

             //   self.scrollViews.contentOffset = CGPointMake(1920,0);
                
                [[[UIManager sharedItems] eventsViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] favoritesViewController].view belowSubview:self.sliderContainerView];
            
            }else if ([view isEqualToString:@"HomeView"]){
                
                NSLog(@"slider value next = %@",view);

//                self.scrollViews.contentOffset = CGPointMake(0,0);
                
                [[[UIManager sharedItems] favoritesViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] homePageViewController].view belowSubview:self.sliderContainerView];
                
            }        }

         }];
    
    
    
}

- (IBAction)previousAction:(id)sender {
    
    NSLog(@"Previous");
    
    [UIView animateWithDuration:0.5 animations:^{
        
        float degrees = 51.43; //the value in degrees
        self.dialImg.transform = CGAffineTransformRotate(self.dialImg.transform, degrees * M_PI/180);
        NSLog(@"center of dial img x = %f and y = %f", self.dialImg.frame.origin.x ,self.dialImg.frame.origin.y);
        
    }completion:^(BOOL finished){
        
        if(x == 0){ // kapag pinaka 1st slider siya
            x = [self.viewControllers count] - 1; // Declare new value for x
            
            [self.view insertSubview:[[UIManager sharedItems] favoritesViewController].view belowSubview:self.sliderContainerView];
            
            NSLog(@"slider value last = %@", [self.viewControllers objectAtIndex:x]);
        }else{
            x = x - 1; // Declare new value for x
          //  NSLog(@"slider value previous = %@", [self.viewControllers objectAtIndex:x]);
            
            NSString *view = [self.viewControllers objectAtIndex:x];
            
            
            if ([view isEqualToString:@"HomeView"]) {
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] artistViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] homePageViewController].view belowSubview:self.sliderContainerView];
                
            }else if ([view isEqualToString:@"NewsFeedView"]) {
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] homePageViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] newsFeedViewController].view belowSubview:self.sliderContainerView];
                
            }else if ([view isEqualToString:@"ArtistView"]) {
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] topDownloadedViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] artistViewController].view belowSubview:self.sliderContainerView];
                
            }else if ([view isEqualToString:@"TopDownloadedView"]){
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] playListViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] topDownloadedViewController].view belowSubview:self.sliderContainerView];
                
            }else if ([view isEqualToString:@"PlayListView"]){
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] eventsViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] playListViewController].view belowSubview:self.sliderContainerView];
                
            }else if ([view isEqualToString:@"EventsView"]){
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] favoritesViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] eventsViewController].view belowSubview:self.sliderContainerView];
                
            }else if ([view isEqualToString:@"FavoritesView"]){
                
                NSLog(@"slider value next = %@",view);
                
                [[[UIManager sharedItems] newsFeedViewController].view removeFromSuperview];
                
                [self.view insertSubview:[[UIManager sharedItems] favoritesViewController].view belowSubview:self.sliderContainerView];
                
            }
        }
        
    }];
}

- (IBAction)hideAction:(id)sender {
    
    if ([hideValue isEqualToString:@"hide"]) {
        NSLog(@"Hide");
        hideValue = @"unhide";
        
        
        
        [UIView animateWithDuration:0.5 animations:^{
            [self.hideBtn setImage:[UIImage imageNamed:@"openSlider.png"] forState:UIControlStateNormal];
             self.sliderContainerView.center = CGPointMake(160, 742);
            
        } completion:^(BOOL finished) {
           
        }];
        
      
        
    }else if ([hideValue isEqualToString:@"unhide"]){
    
        NSLog(@"unhide");
        hideValue = @"hide";
    
        [UIView animateWithDuration:0.5 animations:^{
            [self.hideBtn setImage:[UIImage imageNamed:@"closeSlider.png"] forState:UIControlStateNormal];
            self.sliderContainerView.center = CGPointMake(160, 643);
            
        } completion:^(BOOL finished) {
            
        }];
    }
    
}



#pragma mark - Test;




// You need to override loginView:handleError in order to handle possible errors that can occur during login
- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error {
    NSString *alertMessage, *alertTitle;
    
    // If the user should perform an action outside of you app to recover,
    // the SDK will provide a message for the user, you just need to surface it.
    // This conveniently handles cases like Facebook password change or unverified Facebook accounts.
    if ([FBErrorUtility shouldNotifyUserForError:error]) {
        alertTitle = @"Facebook error";
        alertMessage = [FBErrorUtility userMessageForError:error];
        
        // This code will handle session closures since that happen outside of the app.
        // You can take a look at our error handling guide to know more about it
        // https://developers.facebook.com/docs/ios/errors
    } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession) {
        alertTitle = @"Session Error";
        alertMessage = @"Your current session is no longer valid. Please log in again.";
        
        // If the user has cancelled a login, we will do nothing.
        // You can also choose to show the user a message if cancelling login will result in
        // the user not being able to complete a task they had initiated in your app
        // (like accessing FB-stored information or posting to Facebook)
    } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
        NSLog(@"user cancelled login");
        
        // For simplicity, this sample handles other errors with a generic message
        // You can checkout our error handling guide for more detailed information
        // https://developers.facebook.com/docs/ios/errors
    } else {
        alertTitle  = @"Something went wrong";
        alertMessage = @"Please try again later.";
        NSLog(@"Unexpected error:%@", error);
    }
    
    if (alertMessage) {
        [[[UIAlertView alloc] initWithTitle:alertTitle
                                    message:alertMessage
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    }
}


//------------------------------------



//------------------Sharing a link using the share dialog------------------
- (IBAction)shareLinkWithShareDialog:(id)sender
{
    
    // Check if the Facebook app is installed and we can present the share dialog
    FBLinkShareParams *params = [[FBLinkShareParams alloc] init];
    params.link = [NSURL URLWithString:@"http://192.185.2.177/~tapdash/projects/musicapp/"];
    
    
    // If the Facebook app is installed and we can present the share dialog
    if ([FBDialogs canPresentShareDialogWithParams:params]) {
        
        // Present share dialog
        
        NSLog(@"Facebook App Installed");
        
        [FBDialogs presentShareDialogWithLink:params.link
                                      handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                          if(error) {
                                              // An error occurred, we need to handle the error
                                              // See: https://developers.facebook.com/docs/ios/errors
                                              NSLog(@"Error publishing story: %@", error.description);
                                          } else {
                                              // Success
                                              NSLog(@"result %@", results);
                                          }
                                      }];
        
        
        
        
        
        
        
        // If the Facebook app is NOT installed and we can't present the share dialog
    } else {
        // FALLBACK: publish just a link using the Feed dialog
        
        NSLog(@"Facebook App Not Installed");
        
        // Put together the dialog parameters
        
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       @"Boomerang!", @"name",
                                       @"Please Download.", @"caption",
                                       @"For Indie Bands", @"description",
                                       @"http://192.185.2.177/~tapdash/", @"link",
                                       @"http://pedigreedogtales.com/images/boomerang_logo.png", @"picture",
                                       nil];
        
        // Show the feed dialog
        [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                               parameters:params
                                                  handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                                                      if (error) {
                                                          // An error occurred, we need to handle the error
                                                          // See: https://developers.facebook.com/docs/ios/errors
                                                          NSLog(@"Error publishing story: %@", error.description);
                                                      } else {
                                                          if (result == FBWebDialogResultDialogNotCompleted) {
                                                              // User canceled.
                                                              NSLog(@"User cancelled.");
                                                          } else {
                                                              // Handle the publish feed callback
                                                              NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
                                                              
                                                              if (![urlParams valueForKey:@"post_id"]) {
                                                                  // User canceled.
                                                                  NSLog(@"User cancelled.");
                                                                  
                                                              } else {
                                                                  // User clicked the Share button
                                                                  NSString *result = [NSString stringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
                                                                  NSLog(@"result %@", result);
                                                              }
                                                          }
                                                      }
                                                  }];
        
        
    }
}

//------------------------------------

//------------------Posting a status update using the share dialog------------------
- (IBAction)postStatusUpdateWithShareDialog:(id)sender
{
    
    // Check if the Facebook app is installed and we can present the share dialog
    
    FBLinkShareParams *params = [[FBLinkShareParams alloc] init];
    params.link = [NSURL URLWithString:@"https://developers.facebook.com/docs/ios/share/"];
    
    // If the Facebook app is installed and we can present the share dialog
    if ([FBDialogs canPresentShareDialogWithParams:params]) {
        
        // Present share dialog
        [FBDialogs presentShareDialogWithLink:nil
                                      handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                          if(error) {
                                              // An error occurred, we need to handle the error
                                              // See: https://developers.facebook.com/docs/ios/errors
                                              NSLog(@"Error publishing story: %@", error.description);
                                          } else {
                                              // Success
                                              NSLog(@"result %@", results);
                                          }
                                      }];
        
        // If the Facebook app is NOT installed and we can't present the share dialog
    } else {
        // FALLBACK: publish just a link using the Feed dialog
        // Show the feed dialog
        [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                               parameters:nil
                                                  handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                                                      if (error) {
                                                          // An error occurred, we need to handle the error
                                                          // See: https://developers.facebook.com/docs/ios/errors
                                                          NSLog(@"Error publishing story: %@", error.description);
                                                      } else {
                                                          if (result == FBWebDialogResultDialogNotCompleted) {
                                                              // User cancelled.
                                                              NSLog(@"User cancelled.");
                                                          } else {
                                                              // Handle the publish feed callback
                                                              NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
                                                              
                                                              if (![urlParams valueForKey:@"post_id"]) {
                                                                  // User cancelled.
                                                                  NSLog(@"User cancelled.");
                                                                  
                                                              } else {
                                                                  // User clicked the Share button
                                                                  NSString *result = [NSString stringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
                                                                  NSLog(@"result %@", result);
                                                              }
                                                          }
                                                      }
                                                  }];
    }
}


//------------------------------------

// A function for parsing URL parameters returned by the Feed Dialog.
- (NSDictionary*)parseURLParams:(NSString *)query {
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *val =
        [kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        params[kv[0]] = val;
    }
    return params;
}

//------------------------------------


//------------------Sharing a photo using the Share Dialog ------------------

//- (IBAction)SharePhotoWithShareDialog:(id)sender {
//    
//    // If the Facebook app is installed and we can present the share dialog
//    if([FBDialogs canPresentShareDialogWithPhotos]) {
//        NSLog(@"canPresent");
//        // Retrieve a picture from the device's photo library
//        /*
//         NOTE: SDK Image size limits are 480x480px minimum resolution to 12MB maximum file size.
//         In this app we're not making sure that our image is within those limits but you should.
//         Error code for images that go below or above the size limits is 102.
//         */
//        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
//        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//        [imagePicker setDelegate:self];
//        [self presentViewController:imagePicker animated:YES completion:nil];
//        
//    } else {
//        //The user doesn't have the Facebook for iOS app installed, so we can't present the Share Dialog
//        /*Fallback: You have two options
//         1. Share the photo as a Custom Story using a "share a photo" Open Graph action, and publish it using API calls.
//         See our Custom Stories tutorial: https://developers.facebook.com/docs/ios/open-graph
//         2. Upload the photo making a requestForUploadPhoto
//         See the reference: https://developers.facebook.com/docs/reference/ios/current/class/FBRequest/#requestForUploadPhoto:
//         */
//    }
//    
//    
//}

// When the user is done picking the image
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
//    
//    FBPhotoParams *params = [[FBPhotoParams alloc] init];
//    params.photos = @[img];
//    
//    [FBDialogs presentShareDialogWithPhotoParams:params
//                                     clientState:nil
//                                         handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
//                                             if (error) {
//                                                 NSLog(@"Error: %@", error.description);
//                                             } else {
//                                                 NSLog(@"Success!");
//                                             }
//                                         }];
//    
//}

//------------------------------------

//------------------Sharing a link using API calls------------------





- (IBAction)ShareLinkWithAPICalls:(id)sender {
    // We will post on behalf of the user, these are the permissions we need:
   
    //NSArray *permissionsNeeded = @[@"publish_actions"];
    
    [FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObject:@"publish_actions"]
                                          defaultAudience:FBSessionDefaultAudienceFriends
                                        completionHandler:^(FBSession *session, NSError *error) {
                                            __block NSString *alertText;
                                            __block NSString *alertTitle;
                                            if (!error) {
                                                if ([FBSession.activeSession.permissions
                                                     indexOfObject:@"publish_actions"] == NSNotFound){
                                                    // Permission not granted, tell the user we will not publish
//                                                    alertTitle = @"Permission not granted";
//                                                    alertText = @"Your action will not be published to Facebook.";
//                                                    [[[UIAlertView alloc] initWithTitle:@"jaksdkjsahdjkakds"
//                                                                                message:@"aklsdhlakhdkahdkla"
//                                                                               delegate:self
//                                                                      cancelButtonTitle:@"OK!"
//                                                                      otherButtonTitles:nil] show];
                                                } else {
                                                    // Permission granted, publish the OG story
                                                    [self makeRequestToShareLink];
                                                }
                                                
                                            } else {
                                                // There was an error, handle it
                                                // See https://developers.facebook.com/docs/ios/errors/
                                            }
                                        }];
    
    

//    // Request the permissions the user currently has
//    [FBRequestConnection startWithGraphPath:@"/me/permissions"
//                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//                              if (!error){
//                                  NSDictionary *currentPermissions= [(NSArray *)[result data] objectAtIndex:0];
//                                  NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:@[]];
//                                  
//                                  // Check if all the permissions we need are present in the user's current permissions
//                                  // If they are not present add them to the permissions to be requested
//                                  for (NSString *permission in permissionsNeeded){
//                                      if (![currentPermissions objectForKey:permission]){
//                                          [requestPermissions addObject:permission];
//                                      }
//                                  }
//                                  
//                                  
//                                  
//                                  // If we have permissions to request
//                                  if ([requestPermissions count] > 0){
//                                      // Ask for the missing permissions
//                                      [FBSession.activeSession requestNewPublishPermissions:requestPermissions
//                                                                            defaultAudience:FBSessionDefaultAudienceFriends
//                                                                          completionHandler:^(FBSession *session, NSError *error) {
//                                                                              if (!error) {
//                                                                                  // Permission granted, we can request the user information
//                                                                                  [self makeRequestToShareLink];
//                                                                              } else {
//                                                                                  // An error occurred, handle the error
//                                                                                  // See our Handling Errors guide: https://developers.facebook.com/docs/ios/errors/
//                                                                                  NSLog(@"%@", error.description);
//                                                                                  
//                                                                              }
//                                                                          }];
//                                  } else {
//                                      // Permissions are present, we can request the user information
//                                      [self makeRequestToShareLink];
//                                  }
//                                  
//                              } else {
//                                  // There was an error requesting the permission information
//                                  // See our Handling Errors guide: https://developers.facebook.com/docs/ios/errors/
//                                  NSLog(@"%@", error.description);
//                                  
//                              }
//                          }];
}

- (void)makeRequestToShareLink {
    
    // NOTE: pre-filling fields associated with Facebook posts,
    // unless the user manually generated the content earlier in the workflow of your app,
    // can be against the Platform policies: https://developers.facebook.com/policy
    
    // Put together the dialog parameters
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"Sharing Tutorial", @"name",
                                   @"Build great social apps and get more installs.", @"caption",
                                   @"Allow your users to share stories on Facebook from your app using the iOS SDK.", @"description",
                                   @"https://developers.facebook.com/docs/ios/share/", @"link",
                                   @"http://pedigreedogtales.com/images/boomerang_logo.png", @"picture",
                                   nil];
    
    // Make the request
    [FBRequestConnection startWithGraphPath:@"/me/feed"
                                 parameters:params
                                 HTTPMethod:@"POST"
                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              if (!error) {
                                  // Link posted successfully to Facebook
                                  NSLog(@"result: %@", result);
                                  
                                  NSLog(@"Para Meters in Post = %@", params);
                              } else {
                                  // An error occurred, we need to handle the error
                                  // See: https://developers.facebook.com/docs/ios/errors
                                  NSLog(@"%@", error.description);
                              }
                          }];
    
    
    
    
    
    
}

//------------------------------------

//------------------Posting a status update using API calls------------------

- (IBAction)StatusUpdateWithAPICalls:(id)sender {
    // We will post on behalf of the user, these are the permissions we need:
    NSArray *permissionsNeeded = @[@"publish_actions"];
    
    // Request the permissions the user currently has
    [FBRequestConnection startWithGraphPath:@"/me/permissions"
                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              if (!error){
                                  NSDictionary *currentPermissions= [(NSArray *)[result data] objectAtIndex:0];
                                  NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:@[]];
                                  
                                  // Check if all the permissions we need are present in the user's current permissions
                                  // If they are not present add them to the permissions to be requested
                                  for (NSString *permission in permissionsNeeded){
                                      if (![currentPermissions objectForKey:permission]){
                                          [requestPermissions addObject:permission];
                                      }
                                  }
                                  
                                  // If we have permissions to request
                                  if ([requestPermissions count] > 0){
                                      // Ask for the missing permissions
                                      [FBSession.activeSession requestNewPublishPermissions:requestPermissions
                                                                            defaultAudience:FBSessionDefaultAudienceFriends
                                                                          completionHandler:^(FBSession *session, NSError *error) {
                                                                              if (!error) {
                                                                                  // Permission granted, we can request the user information
                                                                                  [self makeRequestToUpdateStatus];
                                                                              } else {
                                                                                  // An error occurred, handle the error
                                                                                  // See our Handling Errors guide: https://developers.facebook.com/docs/ios/errors/
                                                                                  NSLog(@"%@", error.description);
                                                                              }
                                                                          }];
                                  } else {
                                      // Permissions are present, we can request the user information
                                      [self makeRequestToUpdateStatus];
                                  }
                                  
                              } else {
                                  // There was an error requesting the permission information
                                  // See our Handling Errors guide: https://developers.facebook.com/docs/ios/errors/
                                  NSLog(@"%@", error.description);
                              }
                          }];
}

- (void)makeRequestToUpdateStatus {
    
    // NOTE: pre-filling fields associated with Facebook posts,
    // unless the user manually generated the content earlier in the workflow of your app,
    // can be against the Platform policies: https://developers.facebook.com/policy
    
    [FBRequestConnection startForPostStatusUpdate:@"User-generated status update."
                                completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                    if (!error) {
                                        // Status update posted successfully to Facebook
                                        NSLog(@"result: %@", result);
                                    } else {
                                        // An error occurred, we need to handle the error
                                        // See: https://developers.facebook.com/docs/ios/errors
                                        NSLog(@"%@", error.description);
                                    }
                                }];
}


//------------------------------------

//------------------Handling links back to app link launching app------------------

- (void) _showBackLink {
    if (nil == self.backLinkView) {
        // Set up the view
        UIView *backLinkView = [[UIView alloc] initWithFrame:
                                CGRectMake(0, 30, 320, 40)];
        backLinkView.backgroundColor = [UIColor darkGrayColor];
        UILabel *backLinkLabel = [[UILabel alloc] initWithFrame:
                                  CGRectMake(2, 2, 316, 36)];
        backLinkLabel.textColor = [UIColor whiteColor];
        backLinkLabel.textAlignment = NSTextAlignmentCenter;
        backLinkLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:14.0f];
        [backLinkView addSubview:backLinkLabel];
        self.backLinkLabel = backLinkLabel;
        [self.view addSubview:backLinkView];
        self.backLinkView = backLinkView;
    }
    // Show the view
    self.backLinkView.hidden = NO;
    // Set up the back link label display
    self.backLinkLabel.text = [NSString
                               stringWithFormat:@"Touch to return to %@", self.backLinkInfo[@"app_name"]];
    // Set up so the view can be clicked
    UITapGestureRecognizer *tapGestureRecognizer =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(_returnToLaunchingApp:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [self.backLinkView addGestureRecognizer:tapGestureRecognizer];
    tapGestureRecognizer.delegate = self;
}

- (void)_returnToLaunchingApp:(id)sender {
    // Open the app corresponding to the back link
    NSURL *backLinkURL = [NSURL URLWithString:self.backLinkInfo[@"url"]];
    if ([[UIApplication sharedApplication] canOpenURL:backLinkURL]) {
        [[UIApplication sharedApplication] openURL:backLinkURL];
    }
    self.backLinkView.hidden = YES;
}
//------------------------------------






#pragma mark - Facebook Sharing;



@end
